import * as zip from 'zipjs';

function def_onerror(message) {
  console.error(message);
}

function zipBlob(fn, blob, callback, onerror) {
  zip.createWriter(new zip.BlobWriter("application/zip"),
    function (zipWriter) {
      zipWriter.add(fn, new zip.BlobReader(blob), function () {
        zipWriter.close(callback);
      });
    }, (onerror || def_onerror));
}

function unzipBlob(fn, blob, callback, onerror) {
  zip.createReader(new zip.BlobReader(blob),
    function (zipReader) {
      zipReader.getEntries(function (entries) {
        for (var i = 0; i < entries.length; i++) {
          var obj = entries[i];
          if (!obj.directory && obj.filename === fn) {
            obj.getData(new zip.BlobWriter("text/plain"), function (data) {
              zipReader.close();
              callback(data);
              return;
            });
          }
        }
        callback();  // not found the file
      });
    }, (onerror || def_onerror)
  );
}

function logBlobText(blob) {
  var reader = new FileReader();
  reader.onload = function (e) {
    console.log(e.target.result);
    console.log("--------------");
  };
  reader.readAsText(blob);
}


module.exports = {
  zipBlob: zipBlob,
  unzipBlob: unzipBlob
};
